#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>


//WEXITSTATUS(status)用来获取进程退出的退出码或者状态码，如果失败值为0，成功返回exit或return语句返回的值
//int status = 0;
void Worker(int number)
{
    int *p = NULL;
    int cnt = 10;
    
    while(cnt)
    {
        printf("I am child process, pid: %d, ppid: %d, cnt: %d, number: %d\n", getpid(), getppid(), cnt--, number);
        sleep(1);

        //*p = 100;
        
    }
}
const int n = 10;


int main()
{
    for(int i = 0;i < n; i++)
    {
        pid_t id = fork();
        
        if(id == 0)
        {
            Worker(i);
            //status = i;
            exit(1);
        }
    }

    //等待多个子进程？
    for(int i = 0; i < n; i++)
    {
        int status = 0;
        pid_t rid = waitpid(-1, &status, 0); // pid>0, -1:任意一个退出的子进程
        if(rid > 0){
            printf("wait child %d success, exit code: %d\n", rid, WEXITSTATUS(status));
        }
    }

    return 0;
}

